<?php
/**
 * Created by PhpStorm.
 * User: chenxiaogang
 * Date: 2017/10/25
 * Time: 下午12:24
 */

namespace Coupon\Model;


use Common\Lib\Redis\Redis;
use Common\Model\CommonModel;

/**
 * Class CouponModel
 * @package     Coupon\Model
 * @description 优惠券表模型
 * @parent      后台模块
 * @end
 */
class CouponModel extends CommonModel
{
    const IS_ZERO = 0;//为0
    const SUCCESS = 1;//表示成功，用于status=1表判断
    const FAILURE = 0;//表示失败，用于status=0表判断

    protected $connection = 'DB_CONFIG2';
    protected $tablePrefix = 'system_';

    //自动验证
    protected $_validate = [
        [ 'name', 'require', '优惠券名称不能为空！', 1 ],
        [ 'quantity', '/^\d+$/', '优惠券数量数量必须为正整数', 1 ],
        [ 'effective_days', '/^\d+$/', '有效天数必须为正整数', 1 ],
        [ 'is_single', [ 0, 1 ], '值的范围不正确！', 1, 'in' ],
        [ 'amount', '/^[0-9]+(.[0-9]{1,2})?$/', '请输入合法的数字，小数位不得超过2位', 1 ],
        [ 'status', [ 0, 1, 2 ], '优惠券状态值的范围不正确！', 1, 'in' ],
    ];

    //自动完成
    protected $_auto = [
        [ 'create_time', 'time', 1, 'function' ],//新增时写入时间戳
        [ 'update_time', 'time', 3, 'function' ],//更新时更新写入时间戳
        [ 'createby', 'getCurrentAdminId', 1, 'callback' ],//创建人新增时自动填入
        [ 'updateby', 'getCurrentAdminId', 3, 'callback' ],//新增或者编辑时都更新updateby
    ];

    //返回当前后台用户ID
    public function getCurrentAdminId()
    {
        return get_current_admin_id();
    }

    /**
     * @use          [得到条数]
     * @author       chenxiaogang
     * @end
     * @param $where
     */
    public function getCounts($where)
    {
        $count = $this->alias( 'c' )
            ->field( 'c.id' )
            //->join( 'system_user u on c.createby=u.id', 'left' )
            ->where( $where )
            ->count();
        return $count;
    }

    /**
     * @use          [得到记录]
     * @author       chenxiaogang
     * @end
     * @param $where
     */
    public function getList($where, $limit)
    {
        $where = array_merge( [ ' c.status' => [ 'neq', 2 ] ], $where );
        $data = $this->alias( 'c' )
            ->field( 'c.id,c.name,c.status,c.quantity,c.effective_days,c.is_single,c.amount,c.create_time,c.update_time,c.createby,c.updateby' )
            //->join( 'system_user u on c.createby=u.id', 'left' )
            ->where( $where )
            ->limit( $limit )
            ->select();//结果集
        //dd($this->_sql());die;
        return $data;
    }

    /**
     * @use          [新增优惠券]
     * @author       chenxiaogang
     * @param $post [前台传过来的options数组]
     * @return array
     */
    public function add_coupon($post)
    {
        if($this->create( $post )) {
            if($id = $this->add()) {
                $this->saveToRedis( $this->find( $id ) );//保存到redis
                $resp = [ 'status' => self::SUCCESS, 'msg' => '添加成功！' ];
            } else {
                $resp = [ 'status' => self::FAILURE, 'msg' => '添加失败！' ];
            }
        } else {
            $resp = [ 'status' => self::FAILURE, 'msg' => $this->getError() ];
        }
        return $resp;
    }

    /**
     * @use          [修改优惠券]
     * @author       chenxiaogang
     * @param $post
     * @return array
     */
    public function upd_coupon($post)
    {
        if($this->create( $post )) {
            $id = I( 'get.id' );
            //仅当状态未未启用，才可以修改为已启用
            if($this->where( [ 'id' => $id, 'status' => 0 ] )->save()) {
                $this->saveToRedis( $this->find( $id ) );//保存到redis
                $resp = [ 'status' => self::SUCCESS, 'msg' => '操作成功！' ];
            } else {
                $resp = [ 'status' => self::FAILURE, 'msg' => $this->getError() ];
            }
        } else {
            $resp = [ 'status' => self::FAILURE, 'msg' => $this->getError() ];
        }
        return $resp;
    }

    /**
     * @use          [将优惠券信息存入redis]
     * @author       chenxiaogang
     * @param $data
     * @return void
     */
    public function saveToRedis($data)
    {
        //将已经开启的id存入redis
        if($data['status'] == 1) {
            $redis = Redis::getInstance();//修改指定key的redis
            $redis->sAdd( C( 'COUPON_HAS_SET_REDIS_KEY' ), $data['id'] );//该集合中存放已经开启的id
            $redis->hMSet( C( 'COUPON_REDIS_KEY_PREFIX' ) . $data['id'], $data );
        }
    }

}